/**
 * Copyright 2009-2011 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.myjung.interceptor;

import java.util.List;

import net.myjung.Myjung;
import net.myjung.transaction.ITransactionManager;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.transaction.TransactionStatus;

/**
 * @author Steve M. Jung
 */
public class TransactionInterceptor implements MethodInterceptor {
	protected final Log logger = LogFactory.getLog(getClass());

	private ITransactionManager transactionManager;
	private String readOnlyPrefixes = "get";
	private List<String> readOnlyPrefixList = Myjung.toList(readOnlyPrefixes);

	public TransactionInterceptor() {
		super();
	}
	public Object invoke(MethodInvocation invocation) throws Throwable {
		String methodName = invocation.getMethod().getName();

		TransactionStatus ts = null;
		try {
			if (transactionManager != null) {
				boolean readOnly = false;
				if (!Myjung.isEmpty(readOnlyPrefixList)) {
					for (String readOnlyPrefix : readOnlyPrefixList) {
						if (methodName.startsWith(readOnlyPrefix)) {
							readOnly = true;
							break;
						}
					}
				}
				ts = transactionManager.getStatus(readOnly);
			}

			Object res = invocation.proceed();
			if (ts != null)
				transactionManager.commit(ts);
			return res;
		} catch (Throwable t) {
			if (ts != null)
				transactionManager.rollback(ts);
			throw t;
		}

	}
	public ITransactionManager getTransactionManager() {
		return transactionManager;
	}
	public void setTransactionManager(ITransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}
	public String getReadOnlyPrefixes() {
		return readOnlyPrefixes;
	}
	public void setReadOnlyPrefixes(String readOnlyPrefixes) {
		this.readOnlyPrefixes = readOnlyPrefixes;
		this.readOnlyPrefixList = Myjung.toList(readOnlyPrefixes);
	}
}
